package com.conversationboard.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.database.Database;
import com.conversationboard.database.Queries;
import com.conversationboard.model.User;

@WebServlet(name = "AdminDeleteBanRequestsControllerServlet", urlPatterns = "/Admin/AdminDeleteBanRequestsControllerServlet")
public class AdminDeleteBanRequestsControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -1557185066433219571L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		Connection connection = null;

		try {

			User user = User.get(request.getUserPrincipal().getName());

			if (!SecurityChecks.passes(request, user, this)) {
				return;
			}

			String loginId = request.getParameter("loginid");

			connection = Database.getConnection();
			connection.setAutoCommit(false);

			/* Move them to the backup table */

			try {

				PreparedStatement moveStatement = connection.prepareStatement(Queries.MOVE_BAN_REQUESTS);
				moveStatement.setString(1, loginId);

				moveStatement.executeUpdate();
				moveStatement.close();

				/* Delete them from the main table */

				PreparedStatement deleteStatement = connection.prepareStatement(Queries.REMOVE_BAN_REQUEST_VOTES);
				deleteStatement.setString(1, loginId);

				deleteStatement.executeUpdate();
				deleteStatement.close();

				connection.commit();

			} catch (SQLException e) {
				connection.rollback();
			}

			RequestDispatcher dispatcher = request.getRequestDispatcher("/Admin/AdminViewBanRequestsControllerServlet");
			dispatcher.forward(request, response);

		} catch (SQLException e) {
			throw new ServletException(e);
		} finally {
			try {
				Database.close(connection);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

	}

}
